import { Article, Channel } from '@/types/data'
import { ChannelAction } from '@/types/store'
import { channel } from 'diagnostics_channel'

type ChannelState = {
  userChannels: Channel[]
  allChannels: Channel[]
  active: number
  articles: {
    [key: number]: {
      pre_timestamp: string
      results: Article[]
    }
  }
}
const init: ChannelState = {
  userChannels: [],
  allChannels: [],
  active: 0,
  articles: {},
}
const home = (state = init, action: ChannelAction) => {
  if (action.type === 'home/getUserChannel') {
    return {
      ...state,
      userChannels: action.payload,
      active: action.payload[0].id,
    }
  }
  if (action.type === 'home/updateUserChannel') {
    return {
      ...state,
      userChannels: action.payload,
    }
  }
  if (action.type === 'home/getAllChannel') {
    return {
      ...state,
      allChannels: action.payload,
    }
  }
  if (action.type === 'home/changeActive') {
    return {
      ...state,
      active: action.payload,
    }
  }
  if (action.type === 'home/getArticles') {
    const { channel_id, pre_timestamp, results = [] } = action.payload
    const oldResults = state.articles[channel_id]?.results || []
    return {
      ...state,
      articles: {
        ...state.articles,
        [channel_id]: {
          pre_timestamp,
          results: [...oldResults, ...results],
        },
      },
    }
  }
  if (action.type === 'home/getNewArticles') {
    const { channel_id, pre_timestamp, results = [] } = action.payload
    const oldResults = state.articles[channel_id]?.results || []
    return {
      ...state,
      articles: {
        ...state.articles,
        [channel_id]: {
          pre_timestamp,
          results: [...results],
        },
      },
    }
  }
  return state
}
export default home
